package com.objecteffects.template.web.utils;

import java.util.Random;
import java.util.UUID;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Rusty Wright
 */
@Singleton
public class TemplateCookie {
    @SuppressWarnings("unused")
    private final transient Logger log = LoggerFactory
    .getLogger(TemplateCookie.class);

    private static final String COOKIE_NAME = "template";

    private final Random random = new Random(System.currentTimeMillis());

    private final TemplateHasher templateHasher;

    @Inject
    public TemplateCookie(final TemplateHasher _templateHasher) {
        this.templateHasher = _templateHasher;
    }

    public Cookie makeCookie() {
        final String cookieValue = this.cookieValue();

        return this.makeCookie(cookieValue);
    }

    @SuppressWarnings("static-method")
    public Cookie makeCookie(final String cookieValue) {
        /* cookie maxAge set in UsrLoginActionBean */
        final Cookie cookie =
            new Cookie(TemplateCookie.COOKIE_NAME, cookieValue);

        return cookie;
    }

    /*
     * makes a random hash from the current time and some random
     * numbers.
     */
    private String cookieValue() {
        final StringBuffer result = new StringBuffer();

        final UUID randomUuid = UUID.randomUUID();

        result.append(Long.toString(randomUuid.getLeastSignificantBits()));
        result.append(Long.toString(this.random.nextLong()));
        result.append(Long.toString(randomUuid.getMostSignificantBits()));
        result.append(Long.toString(this.random.nextLong()));

        return this.templateHasher.hash(result.toString());
    }

    public String findHashFromCookies(final HttpServletRequest request) {
        final Cookie cookie = this.findCookie(request);

        if (cookie != null) {
            return cookie.getValue();
        }

        return null;
    }

    @SuppressWarnings("static-method")
    public Cookie findCookie(final HttpServletRequest request) {
        final Cookie[] cookies = request.getCookies();

        if (cookies == null) {
            return null;
        }

        for (final Cookie cookie : cookies) {
            if (TemplateCookie.COOKIE_NAME.equals(cookie.getName())) {
                return cookie;
            }
        }

        return null;
    }
}
